package com.example.demo.pattern.proxy.dynamics;

import com.example.demo.pattern.proxy.staticp.BuyHouse;
import com.example.demo.pattern.proxy.staticp.ProxyService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: demo
 * @description: cglib测试类
 * @author: yby
 * @create: 2020-06-23 18:08
 **/
public class CglibTest implements MethodInterceptor {

    private Object target;

    public CglibTest(Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("start...");
        Object invoke = method.invoke(target, objects);
        System.out.println("end...");
        return invoke;
    }

    public Object getTarget(Object object) { //可以变成 static方法。
        CglibTest cglibTest = new CglibTest(object);
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(cglibTest);
        Object obj = enhancer.create();
        return obj;
    }

    public static void main(String[] args) {
        // 测试当前类
        CglibTest cglibTest = new CglibTest(new BuyHouse());
        ProxyService target = (ProxyService) cglibTest.getTarget(new BuyHouse());
        target.buyHouse();

        // 测试
        /*Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(new BuyHouse().getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("执行开始");
                Object invoke = methodProxy.invokeSuper(o,objects);
                System.out.println("执行结束");
                return invoke;
            }
        });
        ProxyService obj = (ProxyService)enhancer.create();
        obj.buyHouse();*/
    }
    //定义获取代理对象方法

}
